import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';

import 'location_in_confirmation.dart';

class SelectWorkreportrecordList extends StatefulWidget {
  SelectWorkreportrecordList({Key? key,required this.scan}) : super(key: key);

  String scan;

  @override
  _SelectWorkreportrecordListState createState() => _SelectWorkreportrecordListState();
}

class _SelectWorkreportrecordListState extends State<SelectWorkreportrecordList> {

  List dataList = [];
  late var _subscription;

  @override
  void initState() {
    // StoreUtil.write("key", "SelectWorkreportrecordList");
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "SelectWorkreportrecordList")
        .listen(_onEnvent);
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadData(widget.scan);
    });
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) async{
    try {
      var scan = obj["scan"].toString();
      _loadData(scan);
      // _getStation(obj["scan"].toString());
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  @override
  void dispose() {
    StoreUtil.write("key", "locationIn");
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var table = DataTable(
      columns: [
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text("产品编码")),
        DataColumn(label: Text("产品名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("数量")),
        DataColumn(label: Text("产品类型")),
      ],
      rows: this.dataList.map((m) {
        var result = DataRow(
          selected: m['selected'],
            cells: [
          DataCell(Text(m['productionorderno'].toString())),
          DataCell(Text(m['productCode'].toString())),
          DataCell(Text(m['productName'].toString())),
          DataCell(Text(m['productStyle'].toString())),
          DataCell(Text(m['planQTY'].toString())),
          DataCell(Text(m['type'])),
        ],onSelectChanged: (selected){
          setState(() {
            m['selected'] = selected;
          });
          if(selected!){
            _confirmation(m);
          }
        });
        return result;
      }).toList(),
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text('BOM入库选择'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(child: SingleChildScrollView(child:SingleChildScrollView(scrollDirection: Axis.horizontal, child: table),)),
        ],
      ),
    );
    return result;
  }

  Future<String> _changeProductId(productId) async{
    var res = await DynamicDataApi.getModels(model: 'product.product',key: 'product_tmpl_id',val: productId);
    if(res.success!){
      return res.data[0]['id'].toString();
    }else{
      return '';
    }
  }

  _confirmation(Map m) async{
    // 生成对应的产品信息
    var res = await StockQuantOdooApi.HWRequest("product_check",m['productCode']);
    if(!res.success!){
      return ;
    }
    String productId = res.data['product_id'].toString();
    var res1 = await DynamicDataApi.getModels(model: 'product.product',key: 'product_tmpl_id',val: res.data['product_tmpl_id']);
    if(!res1.success!){
      return ;
    }
    StockMoveLine stockMoveLine = StockMoveLine(
      jobType: '2',
      jobTypeName: '工序',
      // jobJson: m['process_name'],
      productionNo: m['productionorderno'],
      productId: productId.toString(),
      productCode: m['productCode'],
      productName: m['productName'],
      productDesc: m['productStyle'],
      planQty: m['planQTY'].toString(),
      productUomId: res1.data[0]['uom_id']!=false?res1.data[0]['uom_id'][0].toString():'',
      productUomName: res1.data[0]['uom_id']!=false?res1.data[0]['uom_id'][1].toString():'',
    );
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: LocationInConfirmation(stockMoveLine: stockMoveLine,isProcess: true,),
      ),
    ).then((v) {
      if (v != null) {
        // _loadData();
      }
    });
  }

  _getData({type,barcode,productCode}) async {
    try{
      var res = await HttpUtil.get(
          "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
      if (!res.success! || res.data.length == 0) {
        CryUtils.message("$barcode生产单号不存在！");
        return;
      }
      if(type == 1){
        dataList.add({
          'selected': false,
          'productionorderno':barcode,
          'productCode':res.data[0]["ProductSpec"],
          'productName':res.data[0]["ProductName"],
          'productStyle':res.data[0]["ProductStyle"],
          'planQTY':res.data[0]["PlanQTY"],
          'type':'成品',
        });
        int index = 1;
        Map codeIndexMap = {};
        for (var element in res.data[0]["PlanItems"]) {
          if(productCode!=null&&productCode!=element["ProductSpec"]){
            continue;
          }
          if(codeIndexMap.containsKey(element["ProductSpec"])){
            dataList[codeIndexMap[element["ProductSpec"]]]['planQTY']+=element["PlanQTY"];
          }else{
            codeIndexMap[element["ProductSpec"]] = index;
            dataList.add({
              'selected': false,
              'productionorderno':barcode,
              'productCode':element["ProductSpec"],
              'productName':element["ProductName"],
              'productStyle':element["ProductStyle"],
              'planQTY':element["PlanQTY"],
              'type':'零件',
            });
            index++;
          }
        }
      }
      if(type == 2){
        if(productCode!=null && productCode == res.data[0]["ProductSpec"]){
          dataList.add({
            'selected': false,
            'productionorderno':barcode,
            'productCode':res.data[0]["ProductSpec"],
            'productName':res.data[0]["ProductName"],
            'productStyle':res.data[0]["ProductStyle"],
            'planQTY':res.data[0]["PlanQTY"],
            'type':'成品',
          });
          return ;
        }
        int index = 0;
        Map codeIndexMap = {};
        for (var element in res.data[0]["PlanItems"]) {
          if(productCode!=null&&productCode!=element["ProductSpec"]){
            continue;
          }
          if(codeIndexMap.containsKey(element["ProductSpec"])){
            dataList[codeIndexMap[element["ProductSpec"]]]['planQTY']+=element["PlanQTY"];
          }else{
            codeIndexMap[element["ProductSpec"]] = index;
            dataList.add({
              'selected': false,
              'productionorderno':barcode,
              'productCode':element["ProductSpec"],
              'productName':element["ProductName"],
              'productStyle':element["ProductStyle"],
              'planQTY':element["PlanQTY"],
              'type':'零件',
            });
            index++;
          }
        }
      }
      if(type == 3){}
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return "";
    }
  }
  _loadData(scan) async {
    dataList = [];
    if(scan.contains("|")){
      // 合单
      List objList = scan.split("|");
      List orderList = objList[0].split(";");
      for (var i = 0; i < orderList.length; i++) {
        await _getData(
          type: 2,
          barcode: orderList[i],
          productCode: objList[1]
        );
      }
    }else{
      // 单生产单号
      await _getData(type: 1, barcode: scan);
    }
    setState(() {});
  }
}
